using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using wicpowerTcpTool.Utilities;
using wicpowerTcpTool.Models;
using System.Diagnostics;
using System.Reflection;

namespace wicpowerTcpTool
{
    /// <summary>
    /// TCP转发工具主窗口
    /// </summary>
    /// <remarks>
    /// 实现TCP端口转发功能，支持多组转发配置管理
    /// 主要功能：
    /// 1. 创建/删除转发组
    /// 2. 启动/停止转发服务
    /// 3. 保存/加载转发配置
    /// 4. 实时监控转发状态
    /// </remarks>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 下一个转发组的ID
        /// </summary>
        private int nextId = 1;
        
        /// <summary>
        /// 所有转发组的集合
        /// </summary>
        private readonly List<ForwardGroup> ForwardGroups = new List<ForwardGroup>();
        
        /// <summary>
        /// 当前选中的IP地址索引
        /// </summary>
        private int globalSelectedIndex = 0;
        
        /// <summary>
        /// 用于UI绑定的转发组集合
        /// </summary>
        private ObservableCollection<ForwardGroup> forwardGroups = new ObservableCollection<ForwardGroup>();

        /// <summary>
        /// 主窗口构造函数
        /// </summary>
        /// <remarks>
        /// 初始化窗口组件后执行：
        /// 1. 初始化IP地址列表
        /// 2. 加载已保存的配置
        /// </remarks>
        public MainWindow()
        {
            InitializeComponent();
            InitializeIPAddresses();
            LoadSavedConfigs();
        }

        /// <summary>
        /// 异步加载已保存的转发配置
        /// </summary>
        /// <remarks>
        /// 从配置文件加载所有转发组配置并初始化UI
        /// 异常处理：
        /// - 配置文件读取失败时显示警告
        /// - 配置加载失败时跳过该配置
        /// </remarks>
        private async void LoadSavedConfigs()
        {
            try
            {
                var configs = ConfigManager.LoadAllConfigs();
                foreach (var config in configs)
                {
                    var group = ConfigManager.LoadForwardGroupConfig(config);
                    if (group != null)
                    {
                        group.Id = nextId++;

                        // 在UI线程中更新界面并设置延迟启动
                        await Dispatcher.InvokeAsync(() =>
                        {
                            ForwardGroups.Add(group);
                            var control = CreateForwardGroupControl(group);
                            forwardGroupsPanel.Children.Add(control);
                            
                            // 3秒后自动启动
                            var timer = new System.Windows.Threading.DispatcherTimer();
                            timer.Interval = TimeSpan.FromSeconds(5);
                            timer.Tick += async (s, e) =>
                            {
                                timer.Stop();
                                try
                                {
                                    await Task.Run(() => group.Start());
                                    
                                    // 更新按钮状态
                                    if (control is Border border && 
                                        border.Child is Grid grid)
                                    {
                                        var button = grid.Children
                                            .OfType<Button>()
                                            .FirstOrDefault(b => b.Content.ToString() == "启动");
                                        if (button != null)
                                        {
                                            button.Content = "停止";
                                            button.Tag = true;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine($"自动启动失败: {ex.Message}");
                                }
                            };
                            timer.Start();
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置失败: {ex.Message}", "警告",
                      MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        /// <summary>
        /// 初始化IP地址下拉框
        /// </summary>
        /// <remarks>
        /// 1. 添加"所有IP地址"选项
        /// 2. 获取系统所有可用IPv4地址
        /// 3. 尝试加载默认IP地址
        /// 4. 设置默认选中项
        /// </remarks>
        private void InitializeIPAddresses()
        {
            cboListenIP.Items.Clear();
            cboListenIP.Items.Add(new ComboBoxItem { Content = "所有IP地址" });

            var ipAddresses = GetSystemIPAddresses();
            foreach (var ip in ipAddresses)
            {
                cboListenIP.Items.Add(new ComboBoxItem { Content = ip.ToString(), Tag = ip });
            }

            // 尝试从配置加载默认IP
            var defaultIP = ConfigManager.GetDefaultListenIP();
            if (defaultIP != null)
            {
                // 查找匹配的IP项
                var matchedItem = cboListenIP.Items.OfType<ComboBoxItem>()
                  .FirstOrDefault(item => item.Tag is IPAddress ip && ip.Equals(defaultIP));

                if (matchedItem != null)
                {
                    cboListenIP.SelectedItem = matchedItem;
                    return;
                }
            }

            // 默认选中逻辑
            if (ipAddresses.Count >= 2)
            {
                // 默认选中第二个IP（跳过"所有IP地址"）
                cboListenIP.SelectedIndex = 2;
            }
            else if (ipAddresses.Count >= 1)
            {
                // 只有一个IP时选中第一个
                cboListenIP.SelectedIndex = 1;
            }
            else
            {
                // 没有IP时选中"所有IP地址"
                cboListenIP.SelectedIndex = 0;
            }
        }


        /// <summary>
        /// 添加转发组按钮点击事件处理
        /// </summary>
        /// <summary>
        /// 添加转发组按钮点击事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        /// <remarks>
        /// 主要流程：
        /// 1. 验证端口输入有效性
        /// 2. 获取选择的IP地址
        /// 3. 检查端口可用性
        /// 4. 验证密令格式
        /// 5. 创建转发组并启动服务
        /// 6. 更新UI并保存配置
        /// </remarks>
        private async void OnAddForwardGroup(object sender, RoutedEventArgs e)
        {
            btnAdd.IsEnabled = false;
            try
            {
                string authToken = txtAuthToken.Text; // 获取密令输入
                if (!int.TryParse(txtPort1.Text, out int port1) || port1 <= 0 || port1 > 65535)
                {
                    MessageBox.Show("请输入有效的监听端口号（1-65535）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (!int.TryParse(txtPort2.Text, out int port2) || port2 <= 0 || port2 > 65535)
                {
                    MessageBox.Show("请输入有效的转发端口号（1-65535）", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 获取选择的IP地址
                IPAddress selectedIP = IPAddress.Any;
                if (cboListenIP.SelectedItem != null && cboListenIP.SelectedIndex > 0) // 直接获取选中项
                {
                    // 确保SelectedItem的类型正确
                    object selectedItem = cboListenIP.SelectedItem;
                    string selectedItemText = selectedItem is ComboBoxItem comboBoxItem
                        ? comboBoxItem.Content?.ToString()
                        : selectedItem?.ToString();

                    if (!string.IsNullOrEmpty(selectedItemText) && !IPAddress.TryParse(selectedItemText, out selectedIP))
                    {
                        MessageBox.Show("无效的IP地址", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }

                // 保存当前输入值，避免在后台线程中访问UI控件
                string remark = txtRemark.Text;

                // 检查端口是否可用
                bool canStart = await Task.Run(() =>
                {
                    if (!ForwardGroup.IsPortAvailable(port1))
                    {
                        MessageBox.Show($"监听端口 {port1} 已被占用", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                        return false;
                    }

                    if (!ForwardGroup.IsPortAvailable(port2))
                    {
                        MessageBox.Show($"转发端口 {port2} 已被占用", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                        return false;
                    }

                    return true;
                });

                if (!canStart)
                {
                    return;
                }

                // 验证密令格式
                if (!string.IsNullOrEmpty(authToken))
                {
                    if (authToken.Length != 8)
                    {
                        ShowTempMessage("密令必须是8位16进制字符(0-9,A-F)",10,10);
                        return;
                    }

                    try
                    {
                        // 测试HEX转换
                        var testBytes = Network.TcpServer.HexStringToBytes(authToken);
                        if (testBytes.Length != 4) // 8位HEX=4字节
                        {
                            ShowTempMessage("密令无效,须8位16进制字符(0-9,A-F)", 10,10);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowTempMessage($"密令错误: {ex.Message}",10,10);
                        return;
                    }
                }

                // 创建新的转发组(传递密令)
                var newGroup = new ForwardGroup(nextId++, port1, port2, remark, authToken);
                newGroup.UpdateListenIP(selectedIP);
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 创建转发组: 端口{port1}->{port2}, 密令: {authToken}");

                // 启动转发服务
                try
                {
                    // 先创建UI控件
                    var groupControl = CreateForwardGroupControl(newGroup);

                    // 启动服务
                    await Task.Run(() => newGroup.Start());

                    // 在UI线程中更新界面
                    await Dispatcher.InvokeAsync(() =>
                    {
                        try
                        {
                            // 添加到列表
                            ForwardGroups.Add(newGroup);

                            // 添加UI控件
                            forwardGroupsPanel.Children.Add(groupControl);

                            // 清空输入框
                            txtPort1.Clear();
                            txtPort2.Clear();
                            txtRemark.Text = "";

                            // 保存配置到INI文件
                            ConfigManager.SaveForwardGroupConfig(selectedIP, port1, port2, remark, authToken);
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 配置已保存: 端口{port1}->{port2}, 密令: {authToken}");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"更新界面时出错: {ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"启动转发服务失败：{ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            finally
            {
                btnAdd.IsEnabled = true;
            }
        }


        /// <summary>
        /// 获取系统所有IPv4地址
        /// </summary>
        /// <summary>
        /// 获取系统所有IPv4地址
        /// </summary>
        /// <returns>IP地址列表</returns>
        /// <remarks>
        /// 包含：
        /// 1. 回环地址(127.0.0.1)
        /// 2. 任意地址(0.0.0.0)
        /// 3. 所有已启用网卡的IPv4地址
        /// </remarks>
        private List<IPAddress> GetSystemIPAddresses()
        {
            var result = new List<IPAddress>();

            // 添加回环地址
            result.Add(IPAddress.Loopback);
            // 添加任意地址
            result.Add(IPAddress.Any);

            // 获取所有网络接口
            foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                // 只获取已启用的以太网和无线网卡
                if (ni.OperationalStatus == OperationalStatus.Up &&
                    (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                     ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211))
                {
                    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                    {
                        // 只添加IPv4地址
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            result.Add(ip.Address);
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 创建转发组的UI控件
        /// </summary>
        /// <param name="group">转发组对象</param>
        /// <returns>转发组UI控件</returns>
        /// <summary>
        /// 创建转发组的UI控件
        /// </summary>
        /// <param name="group">转发组对象</param>
        /// <returns>转发组UI控件</returns>
        /// <remarks>
        /// 控件包含：
        /// 1. 转发组基本信息显示
        /// 2. 端口状态指示灯
        /// 3. 启动/停止按钮
        /// 4. 移除按钮
        /// 5. 数据流指示灯
        /// </remarks>
        private UIElement CreateForwardGroupControl(ForwardGroup group)
        {
            // 参数验证
            if (group == null)
            {
                return new TextBlock { 
                    Text = "错误：转发组配置为空",
                    Foreground = Brushes.Red,
                    Margin = new Thickness(10)
                };
            }

            try
            {
                // 声明控件变量
                Button toggleButton = null;
                
                // 确保关键控件已初始化
                if (cboListenIP == null || forwardGroupsPanel == null)
                {
                    return new TextBlock {
                        Text = "错误：界面未正确初始化",
                        Foreground = Brushes.Red,
                        Margin = new Thickness(10)
                    };
                }

                // 创建边框容器
            var border = new Border
            {
                BorderBrush = Brushes.LightGray,
                BorderThickness = new Thickness(1),
                Margin = new Thickness(0, 0, 0, 5),  // 只保留底部间距
                Padding = new Thickness(10),
                Background = Brushes.White,
                CornerRadius = new CornerRadius(3)  // 添加圆角
            };

            // 创建网格布局
            var grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            // 创建状态面板
            var statusPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0)
            };

            // 转发组信息面板（使用Grid替代原来的TextBlock）
            var infoGrid = new Grid();
            infoGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });  // IP选择下拉框
            infoGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });  // 其他信息

            // 创建IP地址选择下拉框
            var ipComboBox = new ComboBox
            {
                Width = 150,
                Height = 24,
                Margin = new Thickness(0, 0, 10, 0),
                VerticalAlignment = VerticalAlignment.Center
            };

            // 直接拷贝主IP列表的内容
            foreach (ComboBoxItem item in cboListenIP.Items)
            {
                ipComboBox.Items.Add(new ComboBoxItem
                {
                    Content = item.Content,
                    Tag = item.Tag
                });
            }

            // 设置选中项与主IP列表一致
            if (cboListenIP.SelectedItem != null)
            {
                string selectedContent = null;

                if (cboListenIP.SelectedItem is ComboBoxItem selectedItem)
                {
                    selectedContent = selectedItem.Content?.ToString();
                }
                else
                {
                    selectedContent = cboListenIP.SelectedItem.ToString();
                }

                foreach (ComboBoxItem item in ipComboBox.Items)
                {
                    if (item.Content?.ToString() == selectedContent)
                    {
                        ipComboBox.SelectedItem = item;
                        break;
                    }
                }
            }
            else
            {
                ipComboBox.SelectedIndex = globalSelectedIndex;
            }

            // IP变更事件处理
            ipComboBox.SelectionChanged += async (s, e) =>
            {
                if (ipComboBox.SelectedItem is ComboBoxItem selectedItem &&
                    selectedItem.Tag is IPAddress selectedIP)
                {
                    try
                    {
                        // 如果服务正在运行，需要先停止再使用新IP启动
                        if (group.IsServer1Running || group.IsServer2Running)
                        {
                            await Task.Run(() =>
                            {
                              group.Stop();
                              group.UpdateListenIP(selectedIP);
                              group.Start();
                          });
                        }
                        else
                        {
                            group.UpdateListenIP(selectedIP);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"IP变更事件处理异常: {ex.Message}");
                        MessageBox.Show($"更改监听IP失败：{ex.Message}", "错误",
                            MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    Console.WriteLine("IP变更事件处理时SelectedItem类型不正确");
                }
            };

            // 将IP选择下拉框添加到Grid
            Grid.SetColumn(ipComboBox, 0);
            infoGrid.Children.Add(ipComboBox);

            // 创建信息标签
            var infoLabel = new TextBlock
            {
                Text = $"转发组: {group.Id} | 监听端口: {group.Port1} | 转发端口: {group.Port2} | 备注: {group.Remark}" +
                     (string.IsNullOrEmpty(group.AuthToken) ? "" : $" | 密令: {group.AuthToken}"),
                VerticalAlignment = VerticalAlignment.Center,
                TextWrapping = TextWrapping.NoWrap
            };
            Grid.SetColumn(infoLabel, 1);
            infoGrid.Children.Add(infoLabel);

            // 将信息Grid添加到状态面板
            statusPanel.Children.Add(infoGrid);

            //端口工作状态
            // 服务器1状态指示器
            var server1Status = new Ellipse
            {
                Width = 12,
                Height = 12,
                Fill = Brushes.Gray,  // 初始状态为灰色
                Margin = new Thickness(5, 0, 5, 0),
                VerticalAlignment = VerticalAlignment.Center
            };

            // 服务器2状态指示器
            var server2Status = new Ellipse
            {
                Width = 12,
                Height = 12,
                Fill = Brushes.Gray,  // 初始状态为灰色
                Margin = new Thickness(5, 0, 5, 0),
                VerticalAlignment = VerticalAlignment.Center
            };

            // 数据流指示器
            var dataIndicator = new Ellipse
            {
                Width = 12,
                Height = 12,
                Fill = Brushes.Gray,
                Margin = new Thickness(5, 0, 5, 0),
                VerticalAlignment = VerticalAlignment.Center
            };

            // 添加状态指示器和标签到面板
            statusPanel.Children.Add(new TextBlock
            {
                Text = "         | 端口1:",
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 5, 0)
            });
            statusPanel.Children.Add(server1Status);
            statusPanel.Children.Add(new TextBlock
            {
                Text = " | 端口2:",
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(10, 0, 5, 0)
            });
            statusPanel.Children.Add(server2Status);
            statusPanel.Children.Add(new TextBlock
            {
                Text = " | 数据流:",
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(10, 0, 5, 0)
            });

            statusPanel.Children.Add(dataIndicator);
            //三个端口工作状态指示器结束=========================



            // 注册服务器1状态变化事件
            group.Server1StatusChanged += (s, status) =>
            {
                Dispatcher.Invoke(() =>
                {
                        if (status)
                        {
                        // 服务器启动，显示蓝色
                            server1Status.Fill = Brushes.Blue;
                        }
                        else
                        {
                        // 服务器停止，显示灰色
                            server1Status.Fill = Brushes.Gray;
                        }
                    });
            };

            // 注册服务器2状态变化事件
            group.Server2StatusChanged += (s, status) =>
            {
                Dispatcher.Invoke(() =>
                {
                        if (status)
                        {
                        // 服务器启动，显示蓝色
                            server2Status.Fill = Brushes.Blue;
                        }
                        else
                        {
                        // 服务器停止，显示灰色
                            server2Status.Fill = Brushes.Gray;
                        }
                    });
            };

            // 注册客户端1连接状态变化事件
            group.Client1StatusChanged += (s, connected) =>
            {
                Dispatcher.Invoke(() =>
                {
                        if (group.IsServer1Running)  // 只有在服务运行时才改变颜色
                        {
                            server1Status.Fill = connected ? Brushes.Green : Brushes.Blue;
                        }
                    });
            };

            // 注册客户端2连接状态变化事件
            group.Client2StatusChanged += (s, connected) =>
            {
                Dispatcher.Invoke(() =>
                {
                        if (group.IsServer2Running)  // 只有在服务运行时才改变颜色
                        {
                            server2Status.Fill = connected ? Brushes.Green : Brushes.Blue;
                        }
                    });
            };

            // 设置初始状态
            server1Status.Fill = group.IsServer1Running ? 
                (group.IsClient1Connected ? Brushes.Green : Brushes.Blue) : Brushes.Gray;
            server2Status.Fill = group.IsServer2Running ? 
                (group.IsClient2Connected ? Brushes.Green : Brushes.Blue) : Brushes.Gray;

            // 初始化服务状态
            bool isRunning = (group.IsServer1Running || group.IsServer2Running);
            
            // 创建停止/启动按钮
            toggleButton = new Button
            {
                Content = isRunning ? "停止" : "启动",
                Padding = new Thickness(15, 5, 15, 5),
                Margin = new Thickness(5, 0, 5, 0),
                Height = 28,
                Background = Brushes.White,
                BorderBrush = Brushes.Gray,
                Tag = isRunning // 使用Tag存储初始状态
            };

      

            toggleButton.Click += async (s, e) =>
            {
                var button = (Button)s;
                if (button == null || group == null) return;
                
                button.IsEnabled = false;

                try
                {
                    bool currentState = (bool?)button.Tag ?? false;
                    
                    if (currentState)
                    {
                        // 停止服务
                        await Task.Run(() => group.Stop());
                        button.Content = "启动";
                        button.Tag = false;
                    }
                    else
                    {
                        // 启动服务
                        await Task.Run(() => group.Start());
                        button.Content = "停止";
                        button.Tag = true;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"按钮点击事件错误: {ex}");
                    MessageBox.Show($"操作失败：{ex.Message}", "错误", 
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    button.IsEnabled = true;
                }
            };

            // 创建移除按钮
            var removeButton = new Button
            {
                Content = "移除",
                Padding = new Thickness(15, 5, 15, 5),
                Margin = new Thickness(5, 0, 0, 0),
                Height = 28,
                Background = Brushes.White,
                BorderBrush = Brushes.Gray
            };
            removeButton.Click += (s, e) =>
            {
                if (group.IsServer1Running || group.IsServer2Running)
                {
                    var result = MessageBox.Show("转发组正在运行，建议先停止服务再移除。\n\n要强制移除吗？",
                    "服务正在运行",
                    MessageBoxButton.YesNo, MessageBoxImage.Warning);

                    if (result != MessageBoxResult.Yes)
                    {
                        return;
                    }
                }

                if (MessageBox.Show("确定要移除该转发组吗？", "确认",
                    MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try
                    {
                        // 停止服务
                        group.Stop();

                        // 从配置文件中删除
                        ConfigManager.RemoveForwardGroupConfig(group.Port1, group.Port2);
                        Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 已删除配置: 端口{group.Port1}->{group.Port2}");

                        // 从UI移除
                        forwardGroups.Remove(group);
                        forwardGroupsPanel.Children.Remove(border);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 移除配置失败: {ex.Message}");
                        MessageBox.Show($"移除配置失败: {ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            };

            // 设置网格布局
            Grid.SetColumn(statusPanel, 0);
            Grid.SetColumn(toggleButton, 1);  // 使用新的toggleButton替换原来的stopButton
            Grid.SetColumn(removeButton, 2);

            grid.Children.Add(statusPanel);
            grid.Children.Add(toggleButton);  // 使用新的toggleButton
            grid.Children.Add(removeButton);

            border.Child = grid;

            // 注册数据传输事件
            group.DataTransferred += (s, e) =>
            {
                Dispatcher.Invoke(() =>
                {
                    // 数据流指示灯闪烁效果
                        dataIndicator.Fill = Brushes.Yellow;
                        var timer = new System.Windows.Threading.DispatcherTimer
                        {
                            Interval = TimeSpan.FromMilliseconds(100)
                        };
                        timer.Tick += (s2, e2) =>
                        {
                            dataIndicator.Fill = Brushes.Gray;
                            timer.Stop();
                        };
                        timer.Start();
                    });
            };

            return border;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"创建转发组控件时出错：{ex}");
                return new TextBlock { 
                    Text = $"错误：{ex.Message}",
                    Foreground = Brushes.Red,
                    Margin = new Thickness(10)
                };
            }
        }

        private void cboListenIP_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取当前 ComboBox 控件
            ComboBox comboBox = sender as ComboBox;

            if (comboBox != null)
            {
                // 获取选中的项的索引
                int selectedIndex = comboBox.SelectedIndex;
                // 全局变量，用于存储 cboListenIP 的 SelectedIndex
                globalSelectedIndex = selectedIndex;
                // 获取选中的内容
                var selectedItem = comboBox.SelectedItem;

                // 输出选中的索引和内容
                // MessageBox.Show($"选中的索引是: {selectedIndex}, 内容是: {selectedItem}");

                // 根据选中的索引调用 CreateForwardGroupControl 方法
                //  ForwardGroup group = new ForwardGroup(); // 假设你有一个 ForwardGroup 对象
                //  UIElement border = CreateForwardGroupControl(group, selectedIndex);

            }
        }

        private void HexValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            // 验证输入是否为0-9A-Fa-f
            Regex regex = new Regex("[^0-9A-Fa-f]");
            e.Handled = regex.IsMatch(e.Text);

            // 限制最大长度8位
            var textBox = sender as TextBox;
            if (textBox != null && textBox.Text.Length >= 8)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 在窗口右上角显示临时消息提示
        /// </summary>
        /// <param name="message">要显示的提示文本</param>
        /// <param name="seconds">显示持续时间(秒)，默认3秒</param>
        /// <param name="offsetX">距离右侧边距(像素)，默认10px</param>
        /// <param name="offsetY">距离顶部边距(像素)，默认10px</param>
        /// <remarks>
        /// 消息会显示在窗口右上角，带有白色背景和红色文字，
        /// 自动清除同位置旧消息，并在指定时间后自动消失。
        /// </remarks>



        private async void ShowTempMessage(string message, int seconds = 3,
                                           double offsetX = 10, double offsetY = 10)
        {
            var messageBlock = new TextBlock
            {
                Text = message,
                Foreground = Brushes.White,
                Background = Brushes.OrangeRed,
                FontSize = 14,
                FontWeight = FontWeights.Bold,
                Padding = new Thickness(8),
                Opacity = 0.9
            };
            var border = new Border
            {
                Background = Brushes.Black,
                Width = 300,
                Height = 35,
                Child = new TextBlock
                {
                    Text = message,
                    Foreground = Brushes.White,
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center
                }
            };

            //var adornerLayer = AdornerLayer.GetAdornerLayer(this.Content as Visual);
            var adornerLayer = AdornerLayer.GetAdornerLayer(this.RootGrid);
            if (adornerLayer != null)
            {
                //var adorner = new TempMessageAdorner(this, border, offsetX, offsetY);
                var adorner = new TempMessageAdorner(this.RootGrid, border, offsetX, offsetY);
                adornerLayer.Add(adorner);
                await Task.Delay(seconds * 1000);
                adornerLayer.Remove(adorner);
            }
            Debug.WriteLine(adornerLayer != null ? "✅ AdornerLayer OK" : "❌ AdornerLayer is NULL");
          

        }

        //======================

        private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                string text = (string)e.DataObject.GetData(typeof(string));
                Regex regex = new Regex("[^0-9]+");
                if (regex.IsMatch(text))
                {
                    e.CancelCommand();
                }
            }
            else
            {
                e.CancelCommand();
            }
        }

        private void txtAuthToken_TextChanged(object sender, TextChangedEventArgs e)
        {
          // ShowTempMessage("弹出文本",10,20);
           // ShowTempMessage("这是一个提示消息", 3, 20, 20);

        }


    }

}

 